// dynamic_app.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <assert.h>
#include <conio.h>
#include "LoadTests.h"
#include "ThreadTests.h"
#include "..\..\include\vld.h"

// Leaks 6 memory allocations
void LeakDuplicateLeaks() 
{
	// For testing aggregation
	for (int i = 0; i < 3; ++i)
	{
		int* tmp = new int(0x63);
		tmp;
	}
	for (int i = 0; i < 3; ++i)
	{
		int* tmp = new int(0x63);
		tmp;
	}
	// Should report 6 memory leaks
}

int __cdecl ReportHook(int /*reportHook*/, wchar_t *message, int* /*returnValue*/)
{
	OutputDebugString(message);
	return 1;
}

int _tmain(int argc, _TCHAR* argv[])
{
	VLDSetReportHook(VLD_RPTHOOK_INSTALL, ReportHook);
	printf("======================================\n");
	printf("==    TestDllApp  \n");
	printf("======================================\n");

	bool resolve = true;
	bool doThreadTests = true;
	int totalleaks = 0; 
	int tutleaks = 0; 
	int prevleaks = 0;
	char szAnswer[1024] = "";

	printf("\nDo you want to resolve (y/n)?\n");
	printf("Your choice >  ");

#if _MSC_VER>=1400
	gets_s(szAnswer, 1024);  
#else
	gets(szAnswer);  
#endif
	if(strcmp(szAnswer, "y")==0 || 
		strcmp(szAnswer, "Y")==0)
		resolve = true;

	printf("\nDo you want to doThreadTests (y/n)?\n");
	printf("Your choice >  ");
#if _MSC_VER>=1400
	gets_s(szAnswer, 1024);  
#else
	gets(szAnswer);  
#endif
	if(strcmp(szAnswer, "y")==0 || 
		strcmp(szAnswer, "Y")==0)
		doThreadTests = true;


	tutleaks = (int)VLDGetLeaksCount();
	prevleaks = tutleaks;
	RunCosoleDllTest(resolve);    // leaks 6
	totalleaks = (int)VLDGetLeaksCount();
	int leaks1 = totalleaks - prevleaks;
	prevleaks = totalleaks;
	assert(leaks1 == 6);
 
	RunMfcDllTest(resolve); // leaks 7
	totalleaks = (int)VLDGetLeaksCount();
	int leaks2 = totalleaks - prevleaks;
	prevleaks = totalleaks;
	assert(leaks2 == 7);
 
	LeakDuplicateLeaks();       // leaks 6
	totalleaks = (int)VLDGetLeaksCount();
	int leaks3 = totalleaks - prevleaks;
	prevleaks = totalleaks;
	assert(leaks3 == 6);
	
	if (doThreadTests)
	{
		// Creates 3 threads that each leaks 7 allocations. This equals 21
		
		RunLoaderLockTests(resolve);
		totalleaks = (int)VLDGetLeaksCount();
		int leaks4 = totalleaks - prevleaks;
		assert(leaks4 == 21);
	}

	// ..................Total:    31 leaks total
	totalleaks = (int)VLDGetLeaksCount() - tutleaks;
	VLDReportLeaks();
	//VLDMarkAllLeaksAsReported();
	VLDSetReportHook(VLD_RPTHOOK_REMOVE, ReportHook);

	return totalleaks;
}

